package com.ruoyi.web.controller.channel;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.ruoyi.basedata.domain.ConfirmResult;
import com.ruoyi.basedata.domain.WalletKind;
import com.ruoyi.basedata.service.IWalletKindService;
import com.ruoyi.channel.domain.ChannelWallet;
import com.ruoyi.channel.domain.ChannelWalletRSP;
import com.ruoyi.channel.domain.MpChannel;
import com.ruoyi.channel.service.IChannelWalletService;
import com.ruoyi.channel.service.IMpChannelService;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import net.sf.json.JSONObject;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;

/**
 *  信息操作处理
 * 
 * @author ruoyi
 * @date 2019-05-08
 */
@Controller
@RequestMapping("/channel/wallet")
public class ChannelWalletController extends BaseController
{
    private String prefix = "channel/channelWallet";
	
	@Autowired
	private IChannelWalletService channelWalletService;
	@Autowired
	private IMpChannelService mpChannelService;
	@Autowired
	private IWalletKindService walletKindService;

	// 支付状态查询URL - 内部
	@Value("${reqUrlConfig.managerCheckBalance}")
	private String managerCheckBalance;


	@RequiresPermissions("channel:wallet:view")
	@GetMapping()
	public String channelWallet()
	{
	    return prefix + "/channelWallet";
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("channel:wallet:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(ChannelWallet channelWallet, String channelName)
	{
		List<Long> channelIdList = new ArrayList<>();
		// 根据渠道类型名字拿到渠道类型标识
		if (StringUtils.isNotBlank(channelName)) {
			List<MpChannel> mpChannelList = mpChannelService.selectMpChannelByName(channelName);
			if (mpChannelList.size() > 0) {
				for (int i = 0; i < mpChannelList.size(); i++) {
					channelIdList.add(mpChannelList.get(i).getId());
				}
			}
		}
		if (channelIdList.size() == 0) {
			startPage();
			List<ChannelWalletRSP> channelWalletRSPS = channelWalletService.selectChannelWalletRSPList(channelWallet);
			return getDataTable(channelWalletRSPS);
		}else {
			startPage();
			List<ChannelWallet> channelWallets = channelWalletService.seachChannelWalletList(channelIdList);
			return getDataTable(makeChannelWalletRSP(channelWallets));
		}
	}
	
	
	/**
	 * 导出列表
	 */
	@RequiresPermissions("channel:wallet:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ChannelWallet channelWallet)
    {
    	List<ChannelWallet> list = channelWalletService.selectChannelWalletList(channelWallet);
		List<ChannelWalletRSP> channelWalletRSPS = makeChannelWalletRSP(list);
		for (ChannelWalletRSP channelWalletRSP : channelWalletRSPS){
			channelWalletRSP.setAccountBalance(channelWalletRSP.getAccountBalance().divide(new BigDecimal(100)));
			channelWalletRSP.setWaitLiquidatedBalance(channelWalletRSP.getWaitLiquidatedBalance().divide(new BigDecimal(100)));
		}
		ExcelUtil<ChannelWalletRSP> util = new ExcelUtil<ChannelWalletRSP>(ChannelWalletRSP.class);
        return util.exportExcel(channelWalletRSPS, "channelWallet");
    }
	
	/**
	 * 新增
	 */
	@GetMapping("/add")
	public String add()
	{
	    return prefix + "/add";
	}
	
	/**
	 * 新增保存
	 */
	@RequiresPermissions("channel:wallet:add")
	@Log(title = "渠道钱包", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(ChannelWallet channelWallet)
	{
		return toAjax(channelWalletService.insertChannelWallet(channelWallet));
	}

	/**
	 * 修改
	 */
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") Long id, ModelMap mmap)
	{
		ChannelWallet channelWallet = channelWalletService.selectChannelWalletById(id);
		// 根据渠道id 查询对应渠道
		MpChannel mpChannel = mpChannelService.selectMpChannelById(channelWallet.getChannelId().intValue());
		// 自定义封装返回数据
		ChannelWalletRSP channelWalletRSP = new ChannelWalletRSP();
		// 渠道钱包id
		channelWalletRSP.setId(channelWallet.getId());
		// 渠道类型名称
		channelWalletRSP.setChannelName(mpChannel.getName());
		// 渠道类型标识
		channelWalletRSP.setChannelId(channelWallet.getChannelId());

		// 余额
		channelWalletRSP.setAccountBalance(channelWallet.getAccountBalance());
		// 冻结金额
		channelWalletRSP.setWaitLiquidatedBalance(channelWallet.getWaitLiquidatedBalance());
		mmap.put("channelWalletRSP", channelWalletRSP);
	    return prefix + "/edit";
	}
	
	/**
	 * 修改保存
	 */
	@RequiresPermissions("channel:wallet:edit")
	@Log(title = "", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(ChannelWallet channelWallet)
	{		
		return toAjax(channelWalletService.updateChannelWallet(channelWallet));
	}
	
	/**
	 * 删除
	 */
	@RequiresPermissions("channel:wallet:remove")
	@Log(title = "", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{		
		return toAjax(channelWalletService.deleteChannelWalletByIds(ids));
	}


	/**
	 * 封装数据
	 * @param channelWalleList	渠道钱包集合
	 * @return					结果集
	 */
	public List<ChannelWalletRSP> makeChannelWalletRSP(List<ChannelWallet> channelWalleList) {
		// 自定义返回结果数据
		List<ChannelWalletRSP> listRSP = new ArrayList<>();
		for (int i = 0; i < channelWalleList.size(); i++) {
			ChannelWallet wallet = channelWalleList.get(i);
			ChannelWalletRSP channelWalletRSP = new ChannelWalletRSP();
			// 渠道钱包id
			channelWalletRSP.setId(wallet.getId());
			// 查询渠道类型
			startPage();
			MpChannel mpChannelById = mpChannelService.selectMpChannelById(wallet.getChannelId().intValue());
			// 渠道类型名称
			channelWalletRSP.setChannelName(mpChannelById.getName());
			// 渠道类型标识
			channelWalletRSP.setChannelId(mpChannelById.getId());
			// 余额
			channelWalletRSP.setAccountBalance(wallet.getAccountBalance());
			// 冻结金额
			channelWalletRSP.setWaitLiquidatedBalance(wallet.getWaitLiquidatedBalance());

			listRSP.add(channelWalletRSP);
		}
		return listRSP;
	}

	/**
	 * 根据渠道id和钱包类型id  删除渠道钱包
	 */
	@Log(title = "渠道钱包", businessType = BusinessType.DELETE)
	@PostMapping( "/deleteByChannelIdAndWalletKindId")
	@ResponseBody
	public void deleteByChannelIdAndWalletKindId(Long channelId, Long walletKindId)
	{
		channelWalletService.deleteByChannelIdAndWalletKindId(channelId, walletKindId);
	}



	/**
	 * 	余额校正
	 */
	@Log(title = "余额校正", businessType = BusinessType.DELETE)
	@PostMapping( "/balanceCheck")
	@ResponseBody
	public AjaxResult balanceCheck(Integer channelId) {
		MpChannel channel = mpChannelService.selectMpChannelById(channelId);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("channel_code",channel.getCode());
		String  param = jsonObject.toString();
		String result = HttpUtils.sendPost(managerCheckBalance, param, false);
		if (StringUtils.isNotEmpty(result)) {
			JSONObject jsonObjectResult = JSONObject.fromObject(result);
			// ConfirmResult confirmResult = (ConfirmResult) net.sf.json.JSONObject.toBean(jsonObjectResult, ConfirmResult.class);
			if ((int)jsonObjectResult.get("status") == 0) {
				return AjaxResult.success(jsonObjectResult.get("balance"));
			}else {
				return AjaxResult.error(String.valueOf(jsonObjectResult.get("msg")));
			}
		}else {
			return AjaxResult.error("请求失败！");
		}
	}
}
